﻿<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>通用增删改查</title>

	<link href="admin/plugins/bootstrap-3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
	<link href="admin/plugins/material-design-iconic-font-2.2.0/css/material-design-iconic-font.min.css" rel="stylesheet"/>
	<link href="admin/plugins/bootstrap-table-1.11.0/bootstrap-table.min.css" rel="stylesheet"/>
	<link href="admin/plugins/waves-0.7.5/waves.min.css" rel="stylesheet"/>
	<link href="admin/plugins/jquery-confirm/jquery-confirm.min.css" rel="stylesheet"/>
	<link href="admin/plugins/font_73je1zmu39/iconfont.css" rel="stylesheet" />

	<link href="admin/css/common.css" rel="stylesheet"/>

	<style>
		/*将所有元素的默认间距清除，方便自己设置，并且可以消除ul和li的圆点*/
		* {
			margin:0px;
			padding:0px;
		}
		ul {
			background:#fff;
			box-shadow:0 0 10px rgba(0,0,0,0.2);
			/*x坐标，y坐标，模糊程度，颜色*/
			white-space:nowrap;
			/*避免文字换行*/
		}
		ul li {
			position:relative;
		}
		ul li a {
			text-decoration:none;
			color:#777;
			padding:10px 20px;
			display:block;
			background: bottom right no-repeat;
		}
		ul li a:only-child {
			background:none;
		}
		ul li:hover {
			background:#777;
		}
		ul li:hover > a {
			color:#fff;
		}
		ul li:hover > ul {
			display:block;
			/* 鼠标进入母选单後，显示子选单 */
		}
		nav > ul > li {
			display:inline-block;
			/* 使一级选单排成一列 */
		}
		ul ul {
			position:absolute;
			top:100%;
			list-style:none;
			background:#fff;
			box-shadow:0 3px 3px rgba(0,0,0,0.2);
			display:none;
		}
		ul ul ul {
			position:absolute;
			left:100%;
			top:0;
		}
	</style>
</head>
<body>
<div id="main">
	<div id="toolbar">
		<a class="waves-effect waves-button" href="javascript:;" onclick="createAction()"><i class="zmdi zmdi-plus"></i> 新增书籍</a>
		<a class="waves-effect waves-button" href="javascript:;" onclick="updateAction()"><i class="zmdi zmdi-edit"></i> 编辑书籍</a>
<!--		<a class="waves-effect waves-button" href="javascript:;" onclick="deleteAction()"><i class="zmdi zmdi-close"></i> 删除书籍</a>-->
	</div>
	<table id="table"></table>
</div>
<!-- 新增 -->
<div id="template" class="jconfirm jconfirm-light" hidden>
    <div class="jconfirm-bg" style="transition-duration: 0.3s; transition-timing-function: cubic-bezier(0.36, 0.55, 0.19, 1);">
    </div>
    <div class="jconfirm-scrollpane">
        <div class="jc-bs3-container container">
            <div class="jc-bs3-row row">
                <div class="jconfirm-box-container col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
                    <div class="jconfirm-box jconfirm-hilight-shake jconfirm-dark jconfirm-type-animated" role="dialog" aria-labelledby="jconfirm-box93781" tabindex="-1" style="overflow: visible; margin-top: 50px; margin-bottom: 50px; transition-duration: 0.3s; transition-timing-function: cubic-bezier(0.36, 0.55, 0.19, 1); transition-property: all, margin;">
                        <div class="jconfirm-closeIcon" style="display: none;">
                            ×
                        </div>
                        <div class="jconfirm-title-c">
                            <span class="jconfirm-icon-c"></span>
                            <span class="jconfirm-title">新增书籍</span>
                        </div>
                        <div class="jconfirm-content-pane" style="overflow: visible;height: 100%; transition-duration: 0.3s; transition-timing-function: cubic-bezier(0.36, 0.55, 0.19, 1);">
                            <div class="jconfirm-content" id="jconfirm-box93781">
                                <form>
									<div class="form-group">
										<label for="categoryName">类别</label>
										<input id="categoryName" name="categoryName" type="text" class="form-control" style="border: none; outline: none; pointer-events: none;tab-index:'-1'">
										<nav class="" style="z-index: 1" >
											<ul>
												<li><a><span class="iconfont icon-xiala"></span></a>
													<ul name="categoryList">
													</ul>
												</li>
											</ul>
										</nav>
									</div>
									<div class="form-group">
										<label for="book_name">书名</label>
										<input id="book_name" name="book_name" type="text" class="form-control">
									</div>
									<div class="form-group">
										<label for="book_isbn">ISBN</label>
										<input id="book_isbn" name="book_isbn" type="text" class="form-control">
									</div>
									<div class="form-group">
										<label for="book_img">图片</label>
										<input id="book_img" name="book_img" type="text" onclick="$('input[type=file]').click();" class="form-control" >
										<input type="file" onchange="uploadImg(this)" class="form-control" style="display: none">
									</div>
									<div class="form-group">
										<label for="book_author">作者</label>
										<input id="book_author" name="book_author" type="text" class="form-control">
									</div>
									<div class="form-group">
										<label for="book_publishers">出版社</label>
										<input id="book_publishers" name="book_publishers" type="text" class="form-control">
									</div>
									<div class="form-group">
										<label for="book_price">价格</label>
										<input id="book_price" name="book_price" type="number" class="form-control">
									</div>
									<div class="form-group">
										<label for="book_introduction">简介</label>
										<input id="book_introduction" name="book_introduction" type="text" class="form-control">
									</div>
									<div class="form-group">
										<label for="book_time">出版日期</label>
										<input id="book_time" name="book_time" type="text" class="form-control">
									</div>
								</form>
                            </div>
                        </div>
                        <div class="jconfirm-buttons">
                            <button type="button" name="confirm" class="btn waves-effect waves-button">确认</button>
                            <button type="button" onclick="$('#template').attr('hidden', true);" class="btn waves-effect waves-button">取消</button>
                        </div>
                        <div class="jconfirm-clear"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="admin/plugins/jquery.1.12.4.min.js"></script>
<script src="admin/plugins/bootstrap-3.3.0/js/bootstrap.min.js"></script>
<script src="admin/plugins/bootstrap-table-1.11.0/bootstrap-table.min.js"></script>
<script src="admin/plugins/bootstrap-table-1.11.0/locale/bootstrap-table-zh-CN.min.js"></script>
<script src="admin/plugins/waves-0.7.5/waves.min.js"></script>
<script src="admin/plugins/jquery-confirm/jquery-confirm.min.js"></script>

<script src="admin/js/common.js"></script>
<script>
var $table = $('#table');
$(function() {
	$(document).on('focus', 'input', function() {
		$(this).parent().find('label').addClass('active');
	}).on('blur', 'input', function() {
		if ($(this).val() == '') {
			$(this).parent().find('label').removeClass('active');
		}
	});
	// bootstrap table初始化
	// http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/
	$table.bootstrapTable({
		url: "/api/book/v/getBooksAll",
		height: getHeight(),
		striped: true,
		search: true,
		dataType: "json",
		showRefresh: true,
		showToggle: true,
		showColumns: true,
		minimumCountColumns: 2,
		showPaginationSwitch: true,
		clickToSelect: true,
		detailView: true,
		detailFormatter: 'detailFormatter',
		pagination: true,
		paginationLoop: false,
		classes: 'table table-hover table-no-bordered',
		responseHandler: function(res) {
			console.log(res)
			return JSON.parse(res.data);
		},
		// sidePagination: 'server',
		//silentSort: false,
		smartDisplay: false,
		idField: 'id',
		sortName: 'id',
		sortOrder: 'desc',
		escape: true,
		searchOnEnterKey: true,
		maintainSelected: true,
		toolbar: '#toolbar',
		columns: [
			{field: 'state', checkbox: true},
			{field: 'bookIsbn', title: 'ISBN', sortable: true, valign: 'center'},
			{field: 'categoryName', title: '类别', sortable: true, valign: 'center'},
			{field: 'bookImg', title: '图片', sortable: true, valign: 'center'},
			{field: 'bookName', title: '书名', sortable: true, valign: 'center'},
			{field: 'bookAuthor', title: '作者', sortable: true, valign: 'center'},
			{field: 'bookPublishers', title: '出版社', sortable: true, valign: 'center'},
			{field: 'bookPrice', title: '价格', sortable: true, valign: 'center'},
			{field: 'bookIntroduction', title: '简介', sortable: true, valign: 'center'},
			{field: 'bookTime', title: '出版日期', sortable: true, valign: 'center'},
			{field: 'remark', title: '备注', sortable: true, valign: 'center'},
			{field: 'action', title: '操作', valign: 'center', align: 'center', formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false}
		],
		onLoadSuccess: (res) => {
			console.log(res);
		}
	}).on('all.bs.table', function (e, name, args) {
		$('[data-toggle="tooltip"]').tooltip();
		$('[data-toggle="popover"]').popover();  
	});
});
function actionFormatter(value, row, index) {
    return [
        // '<a class="like" href="javascript:void(0)" data-toggle="tooltip" title="Like"><i class="glyphicon glyphicon-heart"></i></a>　',
        '<a class="edit ml10" href="javascript:void(0)" data-toggle="tooltip" title="Edit"><i class="glyphicon glyphicon-edit"></i></a>　'
        // '<a class="remove ml10" href="javascript:void(0)" data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a>'
    ].join('');
}

window.actionEvents = {
    'click .like': function (e, value, row, index) {
        alert('You click like icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .edit': function (e, value, row, index) {
        alert('You click edit icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .remove': function (e, value, row, index) {
        alert('You click remove icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    }
};
function detailFormatter(index, row) {
	var html = [];
	$.each(row, function (key, value) {
		html.push('<p><b>' + key + ':</b> ' + value + '</p>');
	});
	return html.join('');
}
// 新增
function createAction() {
	var categoryList = getCategory(0);
	drawCategory(categoryList);
	$("span.jconfirm-title").text("新增书籍");
	$("#template").attr("hidden", null);
	$("input[name='categoryName']").val("").parentsUntil("form").last().find('label').removeClass('active');
	$("input[name='book_name']").val("").parentsUntil("form").last().find('label').removeClass('active');
	$("input[name='book_isbn']").val("").parentsUntil("form").last().find('label').removeClass('active');
	$("input[name='book_img']").val("").parentsUntil("form").last().find('label').removeClass('active');
	$("input[name='book_author']").val("").parentsUntil("form").last().find('label').removeClass('active');
	$("input[name='book_price']").val("").parentsUntil("form").last().find('label').removeClass('active');
	$("input[name='book_introduction']").val("").parentsUntil("form").last().find('label').removeClass('active');
	$("input[name='book_time']").val("").parentsUntil("form").last().find('label').removeClass('active');
	$("div.jconfirm-buttons button[name='confirm']").off("click").on("click", function () {
		addBook();
	});
}
// 编辑
function updateAction() {
	var rows = $table.bootstrapTable('getSelections');
	if (rows.length != 1) {
		$.confirm({
			title: false,
			content: '请选择一条记录！',
			autoClose: 'cancel|3000',
			backgroundDismiss: true,
			buttons: {
				cancel: {
					text: '取消',
					btnClass: 'waves-effect waves-button'
				}
			}
		});
	} else {
		var categoryList = getCategory(0);
		drawCategory(categoryList);
		$("span.jconfirm-title").text("修改书籍");
		$("#template").attr("hidden", null);
		$("input[name='categoryName']").val(rows[0].categoryName).attr("categoryId", rows[0].categoryParentId).parentsUntil("form").last().find('label').addClass('active');
		$("input[name='book_name']").val(rows[0].bookName).parentsUntil("form").last().find('label').addClass('active');
		$("input[name='book_isbn']").val(rows[0].bookIsbn).parentsUntil("form").last().find('label').addClass('active');
		$("input[name='book_img']").val(rows[0].bookImg).parentsUntil("form").last().find('label').addClass('active');
		$("input[name='book_img']").attr("imgPath",rows[0].bookImg);
		$("input[name='book_author']").val(rows[0].bookAuthor).parentsUntil("form").last().find('label').addClass('active');
		$("input[name='book_price']").val(rows[0].bookPrice).parentsUntil("form").last().find('label').addClass('active');
		$("input[name='book_introduction']").val(rows[0].bookIntroduction).parentsUntil("form").last().find('label').addClass('active');
		$("input[name='book_time']").val(rows[0].bookTime).parentsUntil("form").last().find('label').addClass('active');
		$("input[name='book_publishers']").val(rows[0].bookPublishers).parentsUntil("form").last().find('label').addClass('active');
		$("div.jconfirm-buttons button[name='confirm']").off("click").on("click", function () {
			updateBook();
		});
	}
}
// 删除
function deleteAction() {
	var rows = $table.bootstrapTable('getSelections');
	if (rows.length == 0) {
		$.confirm({
			title: false,
			content: '请至少选择一条记录！',
			autoClose: 'cancel|3000',
			backgroundDismiss: true,
			buttons: {
				cancel: {
					text: '取消',
					btnClass: 'waves-effect waves-button'
				}
			}
		});
	} else {
		$.confirm({
			type: 'red',
			animationSpeed: 300,
			title: false,
			content: '确认删除该书籍吗？',
			buttons: {
				confirm: {
					text: '确认',
					btnClass: 'waves-effect waves-button',
					action: function () {
						var ids = new Array();
						for (var i in rows) {
							ids.push(rows[i].systemId);
						}
						$.alert('删除：id=' + ids.join("-"));
					}
				},
				cancel: {
					text: '取消',
					btnClass: 'waves-effect waves-button'
				}
			}
		});
	}
}
//获取类别
function getCategory(categoryId) {
	var formData = new FormData();
	formData.append("categoryId", categoryId);
	var result;
	$.ajax({
		type: "post",
		url: "/api/category/v/getCategoryByParent",
		dataType: "text",
		data: formData,
		async: false,
		processData: false,
		contentType: false,
		success: data => {
			data = eval('('+ data +')');
			if (data.success) {
				result = JSON.parse(data.data);
			}else {
				result = [];
			}
		},
		error: function (xhr, textStatus, errorThrown) {
			const msg = xhr.responseText;
			console.log(msg);
		}
	});
	return result;
}
//根据类名获取类别
function getCategoryName(categoryName) {
	var formData = new FormData();
	formData.append("name", categoryName);
	var result;
	$.ajax({
		type: "post",
		url: "/api/category/v/getCategoryByName",
		dataType: "text",
		data: formData,
		async: false,
		processData: false,
		contentType: false,
		success: data => {
			data = eval('('+ data +')');
			if (data.success) {
				result = JSON.parse(data.data);
			}else {
				result = [];
			}
		},
		error: function (xhr, textStatus, errorThrown) {
			const msg = xhr.responseText;
			console.log(msg);
		}
	});
	return result;
}

//渲染类别
function drawCategory(categoryList) {
	if (categoryList.length>0) {
		if ($("ul[name='categoryList']").children().length<=0 ||
				(categoryList[0].categoryParent!==0 && $("ul[categoryId='" + categoryList[0].categoryParent + "']").children().length <= 0)) {
			categoryList.forEach((item, index) => {
				if (item.categoryParent === 0) {
					$("ul[name='categoryList']").append("<li categoryId='" + item.categoryId + "' flag=true onmouseover='console.log(123);getChildrenCategory(this)'><a onclick='selectCategory(this," + item.categoryId + ")'>" + item.categoryName + "</a><ul categoryId='" + item.categoryId + "'></ul></li>")
				} else {
					$("ul[categoryId='" + item.categoryParent + "']").append("<li categoryId='" + item.categoryId + "' flag=true onmouseover='console.log(123);getChildrenCategory(this)'><a onclick='selectCategory(this," + item.categoryId + ")'>" + item.categoryName + "</a><ul categoryId='" + item.categoryId + "'></ul></li>");
				}
			});
		}
	}
}
//获得子类
function getChildrenCategory(e) {
	if (e.getAttribute("flag") === "true") {
		e.setAttribute("flag", "false");
		var categoryList = getCategory(e.getAttribute("categoryId"));
		drawCategory(categoryList);
	}
}
//获得选择的类别
function selectCategory(e, categoryId) {
	$("input[name='categoryName']").val($(e).text());
	$("input[name='categoryName']").attr("categoryId", categoryId);
	$(e).parentsUntil("form").last().find('label').addClass('active');
}
//图片上传
function uploadImg(e) {
	console.log(e);
	var formData = new FormData();
	var file = $(e)[0].files[0];
	formData.append("file", file);
	$.ajax({
		url: "/api/upload/v/img",
		type : 'POST',
		cache : false,
		data : formData,
		processData : false,
		contentType : false,
		success: data => {
			if (data.success) {
				$("input[name='book_img']").val(file.name);
				$("input[name='book_img']").attr("imgPath", data.data);
			}else {
				alert(data.msg)
			}
		},
		error: function (xhr, textStatus, errorThrown) {
			const msg = xhr.responseText;
			console.log(msg);
		}
	})
}
//书籍上传
function addBook() {
	var categoryId = $("input[name='categoryName']").last().attr("categoryId");
	var bookIsbn = $("input[name='book_isbn']").last().val();
	var bookImg = $("input[name='book_img']").last().attr("imgPath");
	var bookName = $("input[name='book_name']").last().val();
	var bookPublishers = $("input[name='book_publishers']").last().val();
	var bookPrice = $("input[name='book_price']").last().val();
	var bookAuthor = $("input[name='book_author']").last().val();
	var bookIntroduction = $("input[name='book_introduction']").last().val();
	var bookTime = $("input[name='book_time']").last().val();
	$.ajax({
		type: "post",
		url: "/api/book/a/addBook",
		dataType: "text",
		contentType: "application/json;charset=UTF-8",
		data: JSON.stringify({
			"bookIsbn" : bookIsbn,
			"categoryId": categoryId,
			"bookImg": bookImg,
			"bookName": bookName,
			"bookPublishers": bookPublishers,
			"bookPrice": bookPrice,
			"bookAuthor": bookAuthor,
			"bookIntroduction": bookIntroduction,
			"bookTime": bookTime
		}),
		success: data => {
			data = eval('('+ data +')');
			if (data.success) {
				location.reload();
			}else {
				alert(data.msg);
			}
		},
		error: function (xhr, textStatus, errorThrown) {
			const msg = xhr.responseText;
			console.log(msg);
		}
	});
}
//书籍修改
function updateBook() {
	var categoryId = getCategoryName($("input[name='categoryName']").last().val()).categoryId ;
	var bookIsbn = $("input[name='book_isbn']").last().val();
	var bookImg = $("input[name='book_img']").last().attr("imgPath");
	var bookName = $("input[name='book_name']").last().val();
	var bookPublishers = $("input[name='book_publishers']").last().val();
	var bookPrice = $("input[name='book_price']").last().val();
	var bookAuthor = $("input[name='book_author']").last().val();
	var bookIntroduction = $("input[name='book_introduction']").last().val();
	var bookTime = $("input[name='book_time']").last().val();
	$.ajax({
		type: "post",
		url: "/api/book/a/modifyBook",
		dataType: "text",
		contentType: "application/json;charset=UTF-8",
		data: JSON.stringify({
			"bookIsbn" : bookIsbn,
			"categoryId": categoryId,
			"bookImg": bookImg,
			"bookName": bookName,
			"bookPublishers": bookPublishers,
			"bookPrice": bookPrice,
			"bookAuthor": bookAuthor,
			"bookIntroduction": bookIntroduction,
			"bookTime": bookTime
		}),
		success: data => {
			data = eval('('+ data +')');
			if (data.success) {
				location.reload();
			}else {
				alert(data.msg);
			}
		},
		error: function (xhr, textStatus, errorThrown) {
			const msg = xhr.responseText;
			console.log(msg);
		}
	});
}
</script>
</body>
</html>